package com.ipan.poi.jdbc;

import java.sql.SQLException;
import java.util.Arrays;

/**
 * JDBC异常
 * 
 * @author iPan
 * @version 2013-8-7
 */
public class JDBCException extends java.lang.RuntimeException {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = -6247979002992089093L;
	private String sqlState = null;
	private Integer errorCode = null;
	private String sql = null;
	
	public JDBCException() {
		super();
	}
	
	public JDBCException(String message, Throwable cause) {
		super(message, cause);
	}
	
	public JDBCException(String message) {
		super(message);
	}
	
	public JDBCException(Throwable cause) {
		super(cause);
		if (cause instanceof SQLException) {
			this.sqlState = ((SQLException)cause).getSQLState();
			this.errorCode = ((SQLException)cause).getErrorCode();
		}
	}
	
	public JDBCException(SQLException cause, String sql, Object params[]) {
		StringBuilder msg = new StringBuilder();
		msg.append("SQL: ");
		msg.append(sql);
		if (params == null) {
			msg.append("[]");
		} else {
			msg.append(Arrays.asList(params));
		}
		this.sql = msg.toString();
		this.sqlState = cause.getSQLState();
		this.errorCode = cause.getErrorCode();
	}

	public String getSqlState() {
		return sqlState;
	}

	public Integer getErrorCode() {
		return errorCode;
	}

	public String getSql() {
		return sql;
	}

	@Override
	public String toString() {
		return "JDBCException [sqlState=" + sqlState + ", errorCode=" + errorCode + ", sql=" + sql + "]";
	}
}
